<template>
	<view class="register-container">
	<!-- 	<u-navbar title="登录" @leftClick="navigateBack" safeAreaInsetTop fixed placeholder></u-navbar> -->
		<view class="form-container">
			<u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :labelWidth="80">
				<u-form-item label="账号" prop="username" borderBottom>
					<u--input v-model="model1.username" border="none" placeholder="请输入账号"></u--input>
				</u-form-item>
				<u-form-item label="密码" prop="password" borderBottom>
					<u--input v-model="model1.password" type="password" border="none" placeholder="请输入密码"></u--input>
				</u-form-item>
				<u-form-item label="验证码" prop="captcha" borderBottom>
					<u--input v-model="model1.captcha" border="none" placeholder="请输入验证码"></u--input>
					<view slot="right" class="captcha-box">
				<image :src="captchaImageData" class="captcha-img" @click="refreshCaptcha"></image>
			</view>
				</u-form-item>
			</u--form>
			
			<view class="btn-group">
				<u-button type="primary" text="登录" customStyle="margin-top: 50px" @click="submit"></u-button>
			</view>
			
			<view class="login-options">
				<text class="phone-login" @click="toPhoneLogin">邮箱登录</text>
				<text class="register-link" @click="toRegister">注册账号</text>
				<text class="forgot-link" @click="toForgotPassword">忘记密码</text>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/util/request.js'
	export default {
		data() {
			return {
				captchaImageData: '',
				lastRefreshTime: 0, // 记录上次刷新时间
				isRefreshing: false, // 记录是否正在刷新
				model1: {
					username: '',
					password: '',
					captcha: '',
					uuid: ''
				},
				rules: {
					username: {
						type: 'string',
						required: true,
						message: '请填写账号',
						trigger: ['blur', 'change']
					},
					password: {
						type: 'string',
						required: true,
						min: 6,
						message: '请填写密码',
						trigger: ['blur', 'change']
					},
					captcha: {
						type: 'string',
						required: true,
						len: 4,
						message: '请填写4位验证码',
						trigger: ['blur']
					}
				}
			};
		},
		created() {
			// 在组件创建时生成UUID并保持不变
			this.model1.uuid = this.generateUUID();
		},
		methods: {
			// 生成UUID函数
			generateUUID() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			navigateBack() {
				uni.navigateBack()
			},
			// 刷新验证码
			async refreshCaptcha() {
				// 检查是否正在刷新
				if (this.isRefreshing) {
					uni.$u.toast('正在获取验证码，请稍候');
					return;
				}

				// 检查刷新间隔（60秒）
				const now = Date.now();
				const timeDiff = now - this.lastRefreshTime;
				// if (timeDiff < 3000) { // 60秒内不允许重复刷新
				// 	uni.$u.toast(`请等待${Math.ceil((3000 - timeDiff) / 1000)}秒后再刷新`);
				// 	return;
				// }

				this.isRefreshing = true;
				uni.showLoading({
					title: '获取验证码中'
				});

				try {
					// 生成新的UUID
					this.model1.uuid = this.generateUUID()
					
					// 使用封装的请求方法获取验证码
					request({
						url: `/user-service/user/getCode`,
						method: 'GET',
						data: {
							uuid: this.model1.uuid
						}
					}).then(res => {
						//检查响应数据
						if (!res.data || !res.data.codeBase64) {
							throw new Error('验证码数据格式错误');
						}
						
					// 设置验证码图片数据
					this.captchaImageData = 'data:image/png;base64,' + res.data.codeBase64;
					this.lastRefreshTime = now; // 更新最后刷新时间
					})	
					
				} catch (error) {
					console.error('获取验证码失败:', error);
					// 显示友好的错误提示
					uni.$u.toast('获取验证码失败，请稍后重试');
					// 保持原有验证码图片
				} finally {
					this.isRefreshing = false;
					uni.hideLoading();
				}
			},
			// 提交表单
			submit() {
			
					
					try {

						request({
							url: '/user-service/user/login',
							method: 'POST',
							data: {
								username: this.model1.username,
								password: this.model1.password,
								uuid: this.model1.uuid,
								code: this.model1.captcha
							},
							header: {
								'content-type': 'application/x-www-form-urlencoded' 
							}
						}).then(res => {
							console.log(res)
							// 登录成功
							uni.$u.toast('登录成功');
							
							// 存储用户信息
							const userInfo = {
								userId: res.data.user.userId,
								userAcc: res.data.user.userAcc,
								userName: res.data.user.userName,
							};
							uni.setStorageSync('userInfo', userInfo);
		
							uni.setStorageSync('token', res.data.token);
							// 跳转到首页
							uni.switchTab({
								url: '/pages/home/home'
							});
						});
					} catch (error) {
						console.error(error);
						// 只在验证码错误时刷新验证码
						if (error.response && error.response.data && error.response.data.msg.includes('验证码')) {
							this.refreshCaptcha();
						}
						uni.$u.toast(error.response?.data?.msg || '登录失败，请重试');
					}
				
			},
			// 去手机号登录页面
			toPhoneLogin() {
				uni.navigateTo({
					url: '/pages/login/MailLogin'
				});
			},
			// 去注册页面
			toRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				});
			},
			// 去忘记密码页面
			toForgotPassword() {
				uni.navigateTo({
					url: '/pages/login/forgotPassword'
				});
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			// 初始加载验证码
			this.refreshCaptcha();
		},
	};
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
	
	.register-container {
		min-height: 100vh;
		background-color: #f8f8f8;
		
		.form-container {
			padding: 30rpx;
			
			/deep/ .u-form-item {
				padding: 24rpx 0;
				
				.u-form-item__body__left__content {
					color: #333;
					font-weight: 500;
				}
				
				.u-input {
					height: 80rpx;
				}
			}
			
			.btn-group {
				padding: 40rpx 20rpx;
				
				/deep/ .u-button {
					height: 90rpx;
					border-radius: 45rpx;
					
					&--primary {
						background: linear-gradient(to right, #44ADFB, #0070FF);
						box-shadow: 0 10rpx 20rpx rgba(0, 112, 255, 0.2);
					}
					
					&__text {
						font-size: 32rpx;
						font-weight: 500;
					}
				}
			}
			
			.login-options {
				display: flex;
				justify-content: space-between;
				margin-top: 40rpx;
				padding: 0 20rpx;
				
				.phone-login, .register-link, .forgot-link {
					color: #0070FF;
					font-size: 28rpx;
				}
			}
		}
	}
	
	.captcha-box {
		display: block;
		width: 160px;
		height: 40px;
		margin-left: 20rpx;
		
		
		.captcha-img {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
			object-fit: contain;
		}
	}
</style>
